import { defineStore } from 'pinia'
import http from '@/utils/http'

export const useStore = defineStore('store', {
	state: () => {
		return {
			username: '',
			department: '',
			role: '',
			superAdmin: false,
			access: [],
			routeList: []
		}
	},
	getters: {
		usernumb: () => localStorage.getItem('usernumb'),
		token: () => {
			if(localStorage.getItem('token')) {
				return 'Bearer ' + localStorage.getItem('token')
			} else {
				return null
			}
		}
	},
	actions: {
		setUsernumb: usernumb => localStorage.setItem('usernumb', usernumb),

		setToken: token => localStorage.setItem('token', token),

		logout() {
			localStorage.removeItem('usernumb')
			localStorage.removeItem('token')
			this.username = ''
			this.department = ''
			this.role = ''
			this.superAdmin = false
			this.access = []
			this.routeList = []
		},

		async update() {
			try {
				const res = await http.get('/user/', {
					params: {usernumb: this.usernumb}
				})
				if (res.status === 200) {
					const data = res.data
					this.username = data.username
					this.department = data.department
					this.superAdmin = data.super
					this.role = data.role[0].name
					this.access = []
					if(!data.role) {
						this.access = []
					} else {
						data.role.forEach(role => {
							role.access.forEach(acc => {
								this.access.push(acc.name)
							})
						})
					}
				}
			} catch (err) {
				console.log(err)
			}
		},

		setRouteList(data) {
			this.routeList = data
		},

		hasAccess(access) {
			return this.access.includes(access) || this.superAdmin
		}
	}
})
